//
//  YCQRCodeGenerator.m
//  DemoQRCode
//
//  Created by 唐可雄 on 16/9/2.
//  Copyright © 2016年 swustyc. All rights reserved.
//

#import "YCQRCodeGenerator.h"

@implementation YCQRCodeGenerator

+ (UIImage *)qrImageByCoreImageForString:(NSString *)string imageSize:(CGFloat)size {
    // 1.实例化二维码滤镜
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢复滤镜的默认属性
    [filter setDefaults];
    // 3.通过KVC设置滤镜inputMessage数据
    [filter setValue:[string dataUsingEncoding:NSUTF8StringEncoding] forKey:@"inputMessage"];
    // 4.获取滤镜输出的图像
    CIImage *outputImage = [filter outputImage];
    UIImage *image = [self uiimageFromCIImage:outputImage size:size];
    
    return image;
}

/**
 *  将CIImage转化成指定大小的UIImage
 *
 *  @param image 待转化的CIImage对象
 *  @param size  指定的大小
 *
 *  @return 转化后的结果，UIImage实例
 */
+ (UIImage *)uiimageFromCIImage:(CIImage *)image size:(CGFloat)size {
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.创建bitmap
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.保存bitmap到图片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    
    return [UIImage imageWithCGImage:scaledImage];
}

@end
